package com.jnu.hospitalexamination.interceptor;

import com.jnu.hospitalexamination.annotation.JwtAuth;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

@Slf4j
@Component
public class JwtInterceptor implements HandlerInterceptor {

    private static final String SECRET_KEY = "666222";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        if(request.getMethod().equals("OPTIONS")){
            return true;
        }
        String jwt = request.getHeader("Authorization");
        if(jwt == null || jwt.isEmpty()) {
            return false;
        }
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        if (method.isAnnotationPresent(JwtAuth.class)) {
            log.info("开始token验证:");
            String token = request.getHeader("Authorization");
            if (token == null || !token.startsWith("Bearer ")) {
                log.info("----------------token为空或者不合法----------------------");
                //response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                response.getWriter().write("{\"code\": 401, \"msg\": \"UNAUTHORIZED\"}");
                return false;
            }

            token = token.substring(7);
            try {
                Claims claims = Jwts.parser()
                        .setSigningKey(SECRET_KEY)
                        .parseClaimsJws(token)
                        .getBody();
                request.setAttribute("claims", claims);
                return true;
            }catch (ExpiredJwtException ex){
                log.info("token过期");
                response.getWriter().print("{\"code\":4001,\"msg\":\"token过期，请重新登录\",\"data\":null}");
                return false;
            }catch (SignatureException ex){
                log.info("token被篡改");
                response.getWriter().print("{\"code\":4003,\"msg\":\"token被篡改，请警惕\",\"data\":null}");
                return false;
            }
        }
        log.debug("方法无@JwtAuth注解，继续处理请求.");
        return true;
    }
}
